//
//  RVideoPlayerViewController.m
//  iPlayer
//
//  Created by 侯伟 on 2021/10/28.
//

#import "RVideoPlayerViewController.h"
#import <SJMediaCacheServer/SJMediaCacheServer.h>
#import <SJVideoPlayer/SJVideoPlayer.h>
#import <Masonry/Masonry.h>
#import <SJUIKit/NSAttributedString+SJMake.h>
#import "RCacheObj.h"
#import "RDeviceControlView.h"
#import "RProjectionScreenControlView.h"

static SJControlLayerIdentifier RProjectionScreenIdentifier = 301;
static SJControlLayerIdentifier RDeviceSearchIdentifier = 302;

@interface RVideoPlayerViewController ()<RDeviceControlLayerViewControllerDelegate,RProjectionScreenControlViewDelegate>

@property (nonatomic, strong) SJVideoPlayer *player;
@property(nonatomic, strong)id<SJControlLayerSwitcherObserver> switchgetObserver;

@end

@implementation RVideoPlayerViewController

- (instancetype)init{
    self = [super init];
    if (self) {
        self.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    return self;
}

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeRight;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    MAPPDelegate.allowOrentitaionRotation = YES;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.player vc_viewDidAppear];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    MAPPDelegate.allowOrentitaionRotation = NO;
    [self.player vc_viewWillDisappear];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.player vc_viewDidDisappear];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.player.rotationManager rotate:SJOrientation_LandscapeLeft animated:YES];
    });
}
    
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColor.blackColor;
    
    [self setupPlayer];
    
    NSURL* url = [NSURL URLWithString:self.videoObj.url];
    
    NSURL *playbackURL = [SJMediaCacheServer.shared playbackURLWithURL:url];
    
    self.player.URLAsset = [SJVideoPlayerURLAsset.alloc initWithTitle:self.videoObj.name URL:playbackURL playModel:NULL];
    [self.player play];
}

- (void)setupPlayer{
    
    SJVideoPlayer* player = [SJVideoPlayer player];
    [self.view addSubview:player.view];
    [player.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    _player = player;
    
    player.rotationManager.disabledAutorotation = NO;
    player.rotationManager.autorotationSupportedOrientations = SJOrientationMaskAll;
    

    [player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_Full];
    [player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_Separator];
    [player.defaultEdgeControlLayer.bottomAdapter exchangeItemForTag:SJEdgeControlLayerBottomItem_DurationTime withItemForTag:SJEdgeControlLayerBottomItem_Progress];
    
    SJEdgeControlButtonItem *durationItem = [player.defaultEdgeControlLayer.bottomAdapter itemForTag:SJEdgeControlLayerBottomItem_DurationTime];
    durationItem.insets = SJEdgeInsetsMake(8, 16);
    
    player.defaultEdgeControlLayer.bottomContainerView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.6];
    player.defaultEdgeControlLayer.topContainerView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.6];
    [player.defaultEdgeControlLayer.bottomAdapter reload];
    
    //长按快进
    player.gestureControl.supportedGestureTypes |= SJPlayerGestureTypeMask_LongPress;
    player.rateWhenLongPressGestureTriggered = 2.0;
    player.defaultEdgeControlLayer.draggingProgressPopupView.style = SJDraggingProgressPopupViewStyleFullscreen;
    
    //移除画中画
    if (@available(iOS 14.0, *)) {
        self.player.defaultEdgeControlLayer.automaticallyShowsPictureInPictureItem = NO;
    }
    //投屏
    SJEdgeControlButtonItem* item = [[SJEdgeControlButtonItem alloc] initWithImage:[UIImage imageNamed:@"details_tv"] target:self action:@selector(projectionScreen:) tag:201];
    [player.defaultEdgeControlLayer.topAdapter addItem:item];
    [player.defaultEdgeControlLayer.topAdapter reload];
    [player controlLayerNeedAppear];
    
    
    WeakSelf
    //设备控制层
    [self.player.switcher addControlLayerForIdentifier:RDeviceSearchIdentifier lazyLoading:^id<SJControlLayer> _Nonnull(SJControlLayerIdentifier identifier) {
        StrongSelf
        if (!strongSelf) return nil;
        RDeviceControlView *deviceControl = [RDeviceControlView new];
        deviceControl.delegate = strongSelf;
        return deviceControl;
    }];
    
    //投屏控制层
    [self.player.switcher addControlLayerForIdentifier:RProjectionScreenIdentifier lazyLoading:^id<SJControlLayer> _Nonnull(SJControlLayerIdentifier identifier) {
        StrongSelf
        if (!strongSelf) return nil;
        RProjectionScreenControlView* projectionScreenControlLayer = [RProjectionScreenControlView new];
        projectionScreenControlLayer.delegate = strongSelf;
        return projectionScreenControlLayer;
    }];
    
    self.switchgetObserver = self.player.switcher.getObserver;
    self.switchgetObserver.playerDidEndSwitchControlLayer = ^(id<SJControlLayerSwitcher>  _Nonnull switcher, id<SJControlLayer>  _Nonnull controlLayer) {
        StrongSelf
        if (!strongSelf) return;
        if(switcher.currentIdentifier == RProjectionScreenIdentifier){
            strongSelf.player.resumePlaybackWhenAppDidEnterForeground = NO;
        }else{
            strongSelf.player.resumePlaybackWhenAppDidEnterForeground = YES;
        }
    };
}

//投屏
- (void)projectionScreen:(id)sender{
    [self.player.switcher switchControlLayerForIdentifier:RDeviceSearchIdentifier];
}



#pragma mark  -- RDeviceControlLayerViewControllerDelegate
///
/// 点击空白区域的回调
///
- (void)tappedBlankAreaOnTheControlLayer:(id<SJControlLayer>)controlLayer{
    [self.player.switcher switchControlLayerForIdentifier:SJControlLayer_Edge];
}

///
/// 选择播放设备
///
- (void)choiseDeviceOnTheControlLayer:(id<SJControlLayer>)controlLayer device:(CLUPnPDevice*)device{
    
    id<SJControlLayer> projectionScreenControlLayer = [self.player.switcher controlLayerForIdentifier:RProjectionScreenIdentifier];
    RProjectionScreenControlView* tvcontrolLayer = (RProjectionScreenControlView*)projectionScreenControlLayer;
    tvcontrolLayer.device = device;
    tvcontrolLayer.url = self.videoObj.url;
    tvcontrolLayer.title = self.videoObj.name;
    tvcontrolLayer.duration = self.player.duration;

    [self.player.switcher switchControlLayerForIdentifier:RProjectionScreenIdentifier];
    
    [self.player pause];
}

#pragma mark -- RProjectionScreenControlViewDelegate
///
/// 点击返回
///
- (void)backItemClickOnTheControlLayer:(id<SJControlLayer>)controlLayer{
    [self.player stop];
    [self closeViewControllerAnimated:YES];
}

- (void)stopItemClickOnTheControlLayer:(id<SJControlLayer>)controlLayer{
    [self.player play];
    [self.player.switcher switchControlLayerForIdentifier:SJControlLayer_Edge];
}

/// 切换
- (void)switchItemClickOnTheControlLayer:(id<SJControlLayer>)controlLayer{
    [self.player.switcher switchControlLayerForIdentifier:RDeviceSearchIdentifier];
}


@end
